import type { ConfigEnv, PluginOption, UserConfigExport } from "vite";
import react from "@vitejs/plugin-react";
import Tailwindcss from "@tailwindcss/vite";
import ViteCompression from "vite-plugin-compression";
import { defineConfig, loadEnv } from "vite";
import { fileURLToPath, URL } from "node:url";
import { createHtmlPlugin } from "vite-plugin-html";
import { vitePluginFakeServer } from "vite-plugin-fake-server";
import { webUpdateNotice } from "@plugin-web-update-notification/vite";
import { visualizer } from "rollup-plugin-visualizer";
import { VitePWA } from "vite-plugin-pwa";

// https://vite.dev/config/
export default ({ mode }: ConfigEnv): UserConfigExport => {
  // eslint-disable-next-line node/prefer-global/process
  const env: Record<string, string> = loadEnv(mode, process.cwd());

  return defineConfig({
    server: {
      host: "0.0.0.0",
      cors: true,
      port: 3006,
      proxy: {
        "/api": {
          target: env.VITE_APP_BASE_URL,
          changeOrigin: true,
          ws: false,
          rewrite: (path: string) => path.replace(/^\/api/, "")
        }
      }
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url))
      }
    },
    plugins: [
      react(),
      Tailwindcss(),
      ViteCompression({
        algorithm: env.VITE_APP_PACKING_COMPRESSION === "brotli" ? "brotliCompress" : "gzip",
        ext: env.VITE_APP_PACKING_COMPRESSION === "brotli" ? ".br" : ".gz",
        deleteOriginFile: false
      }),
      vitePluginFakeServer({
        enableDev: env.VITE_APP_DEV_MOCK === "true",
        enableProd: env.VITE_APP_PROD_MOCK === "true",
        logger: false
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: { title: env.VITE_APP_TITLE }
        }
      }),
      env.VITE_APP_PACKING_ANALYSIS_REPORT === "true" && (visualizer({ filename: "stats.html", gzipSize: true, brotliSize: true, open: true }) as PluginOption),
      webUpdateNotice({
        logVersion: true,
        versionType: "build_timestamp",
        checkInterval: 1000,
        hiddenDismissButton: true,
        notificationProps: {
          title: " 🚀 发现新版本",
          description: "系统已发布新版本，是否立即更新获取最新功能？",
          buttonText: "立即更新"
        },
        notificationConfig: {
          primaryColor: "var(--el-color-colorPrimary)"
        }
      }),
      env.VITE_APP_PWA === "true" &&
        VitePWA({
          registerType: "autoUpdate",
          devOptions: { enabled: env.VITE_APP_PWA_DEV === "true" },
          manifest: {
            name: env.VITE_APP_TITLE,
            short_name: env.VITE_APP_TITLE,
            theme_color: "oklch(0.145 0 0)",
            // PWA 的 icon 像素尺寸为 600*600 即可适配以下配置尺寸，建议使用 .png 格式
            icons: [
              {
                src: "/react.png",
                sizes: "192x192",
                type: "image/png"
              },
              {
                src: "/react.png",
                sizes: "512x512",
                type: "image/png"
              },
              {
                src: "/react.png",
                sizes: "512x512",
                type: "image/png",
                purpose: "any maskable"
              }
            ]
          }
        })
    ],
    build: {
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: env.VITE_APP_REMOVE_CONSOLE === "true",
          drop_debugger: true,
          properties: true,
          keep_fnames: true
        }
      },
      sourcemap: false,
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
        }
      }
    }
  });
};
